<template>
  <div class="fx-paragraph">
    <div class="fx-paragraph-content" ref="paragraphContentDom" :style="paragraphContentStyle">
      <span class="fx-paragraph-switch" v-if="handleShowSwitch" @click="handleSwitch">
        {{ currentType ? symbol[0] || '展开' : symbol[1] || '关闭' }}
      </span>
      <slot>{{ content }}</slot>
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, nextTick, PropType, ref, SetupContext, watch } from 'vue'
import { useCheckinPage, useCheckoutPage } from '@/base/hooks'

interface ParagraphProps {
  row: number;
  symbol: string[];
  content: string;
  isCloseBtn: boolean;
}

export default defineComponent({
  name: 'fxParagraph',
  props: {
    symbol: {
      type: Array as PropType<string[]>,
      default: () => ['展开', '关闭']
    },
    row: {
      type: Number as PropType<number>,
      default: 1
    },
    content: {
      type: String as PropType<string>,
      default: ''
    },
    isCloseBtn: {
      type: Boolean as PropType<boolean>,
      default: true
    }
  },
  emits: ['onEllipsis', 'onExpand'],
  setup (props: ParagraphProps, ctx: SetupContext) {
    const clearParagraph = ref<boolean>(false)
    const paragraphContentDom = ref<HTMLElement>()
    const currentType = ref<boolean>(true)
    const paragraphContentStyle = computed(() => {
      return {
        '-webkit-line-clamp': currentType.value ? props.row : 9999
      }
    })

    watch(() => props.row, () => {
      if (currentType.value) nextTick(initParagraph)
    })

    const handleSwitch = () => {
      currentType.value = !currentType.value
      ctx.emit('onExpand', currentType.value)
    }

    const handleShowSwitch = computed(() => {
      if (!clearParagraph.value) return false
      if (!props.isCloseBtn) return currentType.value
      return true
    })

    const initParagraph = () => {
      if (!paragraphContentDom.value) return
      if (paragraphContentDom.value.scrollHeight > paragraphContentDom.value.clientHeight) {
        clearParagraph.value = true
        ctx.emit('onEllipsis')
      } else {
        clearParagraph.value = false
      }
    }

    useCheckinPage(() => {
      initParagraph()
      window.addEventListener('resize', initParagraph)
    })
    useCheckoutPage(() => {
      window.removeEventListener('resize', initParagraph)
    })

    return {
      currentType,
      clearParagraph,
      paragraphContentDom,
      paragraphContentStyle,
      handleSwitch,
      handleShowSwitch
    }
  }
})
</script>
